package com.jwt.demo.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jwt.demo.entity.User;
import com.jwt.demo.service.UserService;
import com.jwt.demo.utils.Result;
import com.jwt.demo.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @ClassName: UserController
 * @Description: User接口类
 * @Author zhouzhixin
 * @Date 2021/8/27
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    UserService userService;

    @Autowired
    public void init(UserService userService) {
        this.userService = userService;
    }

    /**
     * <p>注册用户</p>
     *
     * @param user
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/8/30 11:15
     */
    @PostMapping(value = "/register")
    public Result<?> register(@RequestBody User user) {
        // 非空判断
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return Result.error("用户名或密码不得为空");
        }
        if (CollectionUtils.isNotEmpty(userService.getByUserName(user.getUsername()))) {
            return Result.error("用户名已经存在了，换一个吧");
        }
        // 密码base64加密
        byte[] passwordBytes = user.getPassword().getBytes(StandardCharsets.UTF_8);
        Base64.Encoder encoder = Base64.getEncoder();
        user.setPassword(encoder.encodeToString(passwordBytes));
        // 保存用户
        return userService.save(user) ? Result.success("注册成功") : Result.error("注册失败");
    }

    /**
     * <p>登录</p>
     *
     * @param user
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/8/30 11:15
     */
    @PostMapping(value = "/login")
    public Result<String> login(@RequestBody User user) {
        if (null != userService.checkUser(user)) {
            return Result.success(null, TokenUtil.sign(user));
        } else {
            return Result.error("用户名不存在或密码错误");
        }
    }

    /**
     * <p>验证token唯一接口</p>
     *
     * @param
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/8/30 11:15
     */
    @GetMapping(value = "/test")
    public Result<String> test() {
        return Result.success("test success");
    }

}
